package com.ltmonitor.web.mq;

import com.ltmonitor.service.IOnlineVideoRequestService;
import com.ltmonitor.service.IRealDataService;
import com.ltmonitor.web.vo.VideoConnection;
import com.ltmonitor.web.vo.VideoServerInfo;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.ObjectMessage;
import javax.jms.TextMessage;

/**
 * 获取到最新的视频终端的RTP连接信息
 */
public class RtpConnectionsMessageListener implements MessageListener {
	private static Logger logger = Logger.getLogger(RtpConnectionsMessageListener.class);
	@Autowired
	private IOnlineVideoRequestService onlineVideoRequestService;

	// 当收到消息后，自动调用该方法
	@Override
	public void onMessage(Message message) {

		TextMessage tm = (TextMessage) message;

		try {
			String jsonMessage = tm.getText();
			JSONObject obj = JSONObject.fromObject(jsonMessage);

			VideoServerInfo vi = new VideoServerInfo();
			vi.setMemoryUsed(obj.getInt("MemoryUsed"));
			vi.setCpuLoad(obj.getInt("CpuLoad"));

			JSONArray j =  obj.getJSONArray("connections");

			for(int m = 0; m < j.size(); m++)
			{
				JSONObject o = j.getJSONObject(m);
				VideoConnection c = new VideoConnection();
				String simNo = o.getString("SimNo");
				if(simNo != null && simNo.length() > 11)
					simNo = simNo.substring(1);
				c.setSimNo(simNo);
				c.setChannelId(o.getInt("ChannelId"));
				c.setQueueNum(o.getInt("QueueNum"));
				c.setDataUsage(o.getInt("DataUsage"));
				c.setCreateDate(o.getString("CreateDate"));
				c.setOnlineDate(o.getString("OnlineDate"));
				c.setGovUserPlaying(o.getBoolean("GovUserPlaying"));
				vi.getConnections().add(c);
			}
			this.onlineVideoRequestService.updateVideoServerInfo(vi);
			//logger.error("监听到了文本消息：\t" + tm.getText());
			//HelloHandler.broadcast(new TextMessage("报警了"));
			// do something ...
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
		}
	}

}
